package com.ehotting.eaf.netty.client;


import com.ehotting.eaf.netty.code.ByteToCommandDecoder;
import com.ehotting.eaf.netty.code.ByteToCommandEncoder;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class ClientInitializer extends ChannelInitializer<SocketChannel> {

	protected ConnectorIdleStateTrigger idleStateTrigger;  
	
	protected ChannelInboundHandler channelInboundHandler;
	
	/**读操作空闲秒数**/
	protected Integer readIdle;
	/**写操作空闲秒数**/
	protected Integer writeIdle;
	/**读写空闲秒数**/
	protected Integer allIdle;
	/**
	 * 编码器，有默认值
	 */
	private MessageToByteEncoder<String> byteToCommandEncoder = new ByteToCommandEncoder();
	/**
	 * 解码器，有默认值
	 */
	private ByteToMessageDecoder byteToCommandDecoder = new ByteToCommandDecoder();

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new IdleStateHandler(readIdle, writeIdle, allIdle, TimeUnit.SECONDS));
		pipeline.addLast(new ByteToCommandEncoder());
		pipeline.addLast(new ByteToCommandDecoder());
		pipeline.addLast(idleStateTrigger);
        pipeline.addLast(channelInboundHandler);
    }
    
	public void setChannelInboundHandler(ChannelInboundHandler channelInboundHandler) {
		this.channelInboundHandler = channelInboundHandler;
	}

	public void setIdleStateTrigger(ConnectorIdleStateTrigger idleStateTrigger) {
		this.idleStateTrigger = idleStateTrigger;
	}

	public void setReadIdle(Integer readIdle) {
		this.readIdle = readIdle;
	}

	public void setWriteIdle(Integer writeIdle) {
		this.writeIdle = writeIdle;
	}

	public void setAllIdle(Integer allIdle) {
		this.allIdle = allIdle;
	}

	public void setByteToCommandEncoder(MessageToByteEncoder<String> byteToCommandEncoder) {
		this.byteToCommandEncoder = byteToCommandEncoder;
	}

	public void setByteToCommandDecoder(ByteToMessageDecoder byteToCommandDecoder) {
		this.byteToCommandDecoder = byteToCommandDecoder;
	}
}